package Pet.Management.controller;

import java.util.List;
import java.util.Map;
import java.util.Optional;
import java.util.stream.Collectors;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Pageable;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;

import Pet.Management.domain.dto.AcceptorDTO;
import Pet.Management.domain.entity.PetCareAcceptor;
import Pet.Management.domain.entity.User;
import Pet.Management.repository.PetCareAcceptorRepository;
import Pet.Management.repository.UserRepository;
import Pet.Management.service.MessageService;
import Pet.Management.domain.entity.PetCareOrder;
import Pet.Management.domain.entity.TaskNode;
import Pet.Management.service.OrderAcceptService;

@RestController
@RequestMapping("/api/pet-care")
public class PetCareAcceptorController {

    @Autowired
    private PetCareAcceptorRepository acceptorRepository;
    
    @Autowired
    private UserRepository userRepository;
    
    @Autowired
    private MessageService messageService;
    
    @Autowired
    private OrderAcceptService orderAcceptService;
    
    /**
     * 获取接单者列表
     */
    @GetMapping("/acceptors")
    public ResponseEntity<Map<String, Object>> getAcceptors(
            @RequestParam(defaultValue = "0") int page,
            @RequestParam(defaultValue = "10") int size,
            @RequestParam(required = false) String search) {
        
        Pageable pageable = PageRequest.of(page, size);
        Page<PetCareAcceptor> acceptorPage;
        
        if (search != null && !search.isEmpty()) {
            acceptorPage = acceptorRepository.searchAcceptors(search, pageable);
        } else {
            acceptorPage = acceptorRepository.findByStatus(0, pageable);
        }
        
        List<AcceptorDTO> acceptorDTOs = acceptorPage.getContent().stream()
            .map(this::convertToDTO)
            .collect(Collectors.toList());
        
        Map<String, Object> response = Map.of(
            "acceptors", acceptorDTOs,
            "currentPage", acceptorPage.getNumber(),
            "totalItems", acceptorPage.getTotalElements(),
            "totalPages", acceptorPage.getTotalPages()
        );
        
        return ResponseEntity.ok(response);
    }
    
    /**
     * 联系接单者（发送私信）
     */
    @PostMapping("/contact/{acceptorId}")
    public ResponseEntity<?> contactAcceptor(
            @PathVariable Long acceptorId,
            @RequestParam Long userId,
            @RequestBody Map<String, String> payload) {
        
        String message = payload.get("message");
        if (message == null || message.isEmpty()) {
            return ResponseEntity.badRequest().body(Map.of("error", "消息内容不能为空"));
        }
        
        Optional<PetCareAcceptor> acceptorOpt = acceptorRepository.findById(acceptorId);
        if (!acceptorOpt.isPresent()) {
            return ResponseEntity.notFound().build();
        }
        
        Optional<User> senderOpt = userRepository.findById(userId);
        if (!senderOpt.isPresent()) {
            return ResponseEntity.badRequest().body(Map.of("error", "用户不存在"));
        }
        
        PetCareAcceptor acceptor = acceptorOpt.get();
        
        // 发送私信
        messageService.sendPrivateMessage(
            userId,
            acceptor.getUser().getId(),
            "宠物托管咨询",
            message
        );
        
        return ResponseEntity.ok(Map.of("message", "消息已发送"));
    }
    
    /**
     * 将PetCareAcceptor实体转换为AcceptorDTO
     */
    private AcceptorDTO convertToDTO(PetCareAcceptor acceptor) {
        AcceptorDTO dto = new AcceptorDTO();
        dto.setId(acceptor.getId());
        dto.setUserId(acceptor.getUser().getId());
        dto.setAcceptorName(acceptor.getUser().getUsername());
        dto.setGoodAtPetType(acceptor.getGoodAtPetType());
        dto.setExperience(acceptor.getExperience());
        dto.setContactInfo(acceptor.getContactInfo());
        dto.setStatus(acceptor.getStatus());
        dto.setRating(acceptor.getRating());
        dto.setTotalOrders(acceptor.getTotalOrders());
        dto.setCreateTime(acceptor.getCreateTime());
        return dto;
    }

    @GetMapping("/orders/available")
    public ResponseEntity<List<PetCareOrder>> getAvailableOrders(@RequestParam Long userId) {
        List<PetCareOrder> orders = orderAcceptService.getAvailableOrders(userId);
        return ResponseEntity.ok(orders);
    }

    @GetMapping("/orders/accepted")
    public ResponseEntity<List<PetCareOrder>> getAcceptedOrders(@RequestParam Long userId) {
        List<PetCareOrder> orders = orderAcceptService.getAcceptedOrders(userId);
        return ResponseEntity.ok(orders);
    }

    @PostMapping("/orders/{orderId}/accept")
    public ResponseEntity<?> acceptOrder(
            @PathVariable Long orderId,
            @RequestParam Long acceptorId,
            @RequestBody List<TaskNode> taskNodes) {
        try {
            orderAcceptService.acceptOrder(orderId, acceptorId, taskNodes);
            return ResponseEntity.ok().build();
        } catch (RuntimeException e) {
            return ResponseEntity.badRequest().body(e.getMessage());
        }
    }

    @PostMapping("/orders/{orderId}/cancel")
    public ResponseEntity<?> cancelAcceptance(
            @PathVariable Long orderId,
            @RequestParam Long acceptorId) {
        try {
            orderAcceptService.cancelAcceptance(orderId, acceptorId);
            return ResponseEntity.ok().build();
        } catch (RuntimeException e) {
            return ResponseEntity.badRequest().body(e.getMessage());
        }
    }

    @GetMapping("/orders/{orderId}/can-accept")
    public ResponseEntity<Boolean> canAcceptOrder(
            @PathVariable Long orderId,
            @RequestParam Long acceptorId) {
        boolean canAccept = orderAcceptService.canAcceptOrder(orderId, acceptorId);
        return ResponseEntity.ok(canAccept);
    }
} 